import Api, {GET_OSS_CONFIG} from './api.js';

export function ossupload(success){

    wx.chooseImage({
        count:1,
        success: function(res) {
            Api.fetch(GET_OSS_CONFIG,{},config=>{
                let img = res.tempFilePaths[0];
                let img_name = config.dir + random_string(10,'cshow_') + get_suffix(img)
                   
                wx.uploadFile({
                    url: config.host,
                    filePath: img,
                    name: 'file',
                    formData:{
                        key: img_name,
                        policy: config.policy,
                        OSSAccessKeyId: config.accessid,
                        success_action_status:'200',
                        signature: config.signature
                    },
                    success:function(img){
                        success && success(img_name);
                    },
                    fail:function(fail){
                        
                    }
                })
            })
        },
    })
}


export function get_suffix(filename) {
    let pos = filename.lastIndexOf('.')
    let suffix = ''
    if (pos != -1) {
        suffix = filename.substring(pos)
    }
    return suffix;
}

function random_string(len,prefix) {
    len = len || 32;
    prefix = prefix || 'user_';
    let chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
    let maxPos = chars.length;
    let pwd = '';
    for (let i = 0; i < len; i++) {
        pwd += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return prefix + pwd;
}